'use strict';

const BaseService = require('../../libs/base/BaseService');
const MySQLServer = require('./MySQLServer');
const Code = require('../../config/code');
const Utils = require('../utils/Utils');

/**
 * MySQL服务，提供MySQL数据库操作
 */
class MySQL extends BaseService {
  /**
   * 构造函数
   */
  constructor() {
    super('MySQL');
    this.mysqlserver = new MySQLServer();
  }

  /**
   * 初始化服务
   */
  async init() {
    console.log(`[MySQL] 服务初始化中...`);
    this.mysqlserver.init();
  }
  /**
   * 根据平台唯一id登录
   */
  async loginByPlatformId(id, platform) {
    if (!id || !platform) {
      return Code.PARAM_ERROR;
    }
    //防止id重复，先做一下处理
    id = `${platform}_${id}`;
    const info = await this.mysqlserver.query(`SELECT * FROM users WHERE openid = ? and platform = ?`, [id, platform]);
    if (info.length > 0) {
      return { code: Code.SUCCESS, data: info[0] };
    } else {
      return Code.MYSQL_USER_NOT_EXIST;
    }
  }
  /**
   * 根据本系统唯一id登录
   */
  async loginByPid(pid) {
    if (!pid) {
      return Code.PARAM_ERROR;
    }
    //防止id重复，先做一下处理
    const info = await this.mysqlserver.query(`SELECT * FROM users WHERE pid = ? `, [pid]);
    if (info.length > 0) {
      return { code: Code.SUCCESS, data: info[0] };
    } else {
      return Code.MYSQL_USER_NOT_EXIST;
    }
  }
  async login(name, password) {
    const info = await this.mysqlserver.query(`SELECT * FROM users WHERE nickName = ?`, [name]);
    if (info.length > 0) {
      if (Utils.verifyPassword(password, info[0].password_hash)) {
        return info[0];
      } else {
        return { code: 1, info: '用户名不存在' };
      }
    } else {
      return { code: 1, info: '用户名不存在' };
    }
  }
  async regeditWXPlayer(data) {
    const info = await this.mysqlserver.insert("users", data);
    return info;
  }
}

module.exports = MySQL; 